from xml.dom.minidom import parse
from os.path import dirname, join
import AiImage
import AiPage
import sys
sys.path.append("../reasoning")
from AiReasoning import reason

def loadTBMP():
    return AiBook("../../books/TheBraveMonkeyPirate/TheBraveMonkeyPirate.xml")

class AiBook:
    def __init__(self, xmlFilename):
        pathToBook = dirname(xmlFilename)
        xml = parse(xmlFilename)

        # TODO replace with xsd conformaiton check:
        assert xml.documentElement.tagName == "book"

        self.title = xml.documentElement.getAttribute("title")
        self.author = xml.documentElement.getAttribute("author")

        ## Load Coverpage
        for cpage in xml.documentElement.getElementsByTagName("coverpage"):
            src = cpage.getElementsByTagName("img").item(0).getAttribute("src")
            self.coverimage = AiImage.loadImageFromFile(join(pathToBook, src))

        self.pages = []
        self.nrOfPages = 0
        ## Load Pages
        for page in xml.documentElement.getElementsByTagName("page"):
            src = page.getElementsByTagName("img").item(0).getAttribute("src")
            img = AiImage.loadImageFromFile(join(pathToBook, src))
            txt = page.getElementsByTagName("text").item(0).firstChild.data
            pnr = int(page.getAttribute("nr"))

            self.pages.append(AiPage.AiPage(pnr, img, txt, self))
            self.nrOfPages += 1

        self.blobsTraced = False
        self.nlp = False
        self.em = False

    def findBlobs(self):
        for page in self.pages:
            page.findBlobs()
        self.blobsTraced = True

    def getBlobById(self,(pagenr, blobnr)):
        b = self.pages[pagenr-1].blobs[blobnr]
        if __debug__:
            assert b.id == (pagenr, blobnr)

        return b

    def doNLP(self):
        for page in self.pages:
            page.findWords()
        self.nlp = True

    def doEM(self):
        #TODO: insert andreas' stuff.
        reason(self.pages)
        for page in self.pages:
            page.generateTags()
        self.em = True 

